const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const http = require('http');
const wsServer = require('./utils/websocket');
const app = express();

// 创建 HTTP server
const server = http.createServer(app);

// 初始化 WebSocket 服务器
wsServer.initialize(server);

// 中间件配置
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

// 导入路由
const adminRoutes = require('./routes/admin');
const bookRoutes = require('./routes/books');
const draftRoutes = require('./routes/drafts');
const notificationRoutes = require('./routes/notifications');
const reportRoutes = require('./routes/reports');
const userRoutes = require('./routes/users');
const statisticsRoutes = require('./routes/statistics');

// 注册路由
app.use('/api/admin', adminRoutes);
app.use('/api/books', bookRoutes);
app.use('/api/drafts', draftRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/reports', reportRoutes);
app.use('/api/users', userRoutes);
app.use('/api/statistics', statisticsRoutes);

// 基础路由
app.get('/', (req, res) => {
  res.json({ message: '成功启动啦' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: '看来出了点问题' });
});

// 只在非测试环境下启动服务器
if (process.env.NODE_ENV !== 'test') {
  server.listen(3000, () => {
    console.log(`服务器启动成功，端口：${3000}`);
  });
}

module.exports = { app, server }; 
